# -*- coding: utf-8 -*-
import pinyin
from odoo import fields, models, api
from odoo.exceptions import ValidationError


class TourCity(models.Model):
    """城市"""

    _name = 'tour.city'
    _description = u'城市'

    name = fields.Char(string=u'名称')
    code = fields.Char(string=u'编码', compute='_compute_code', store=True)  # 存储名称的拼音首字母
    active = fields.Boolean(u'有效', default=True)

    @api.constrains('name')
    def _check_name(self):
        for record in self:
            count = self.search_count([('name', '=', record.name)])
            if count > 1:
                raise ValidationError(u'城市名称已经存在！')

    @api.multi
    def _compute_code(self):
        for c in self:
            c.code = pinyin.get_initial(self.name).replace(' ', '')
